package com.yc.qunxing.web;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yc.qunxing.clients.DriverAction;
import com.yc.qunxing.clients.UserAction;
import com.yc.qunxing.entity.*;
import com.yc.qunxing.entity.vo.OrderDetails;
import com.yc.qunxing.entity.vo.OrderDetailsDriver;
import com.yc.qunxing.entity.vo.RouteFrequency;
import com.yc.qunxing.result.Result;
import com.yc.qunxing.service.IDriversService;
import com.yc.qunxing.service.IOrdersService;
import com.yc.qunxing.service.IUserRatingsService;
import com.yc.qunxing.service.IUsersService;
import com.yc.qunxing.websocket.WebSocketServer;
import com.yc.qunxing.websocket.WebSocketServerDriver;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 鹏哥
 * @since 2024-05-23
 */
@RestController
@RequestMapping("/orders")
public class OrderController {

    @Autowired
    public IOrdersService iOrdersService;
    @Autowired
    private WebSocketServer webSocketServer;
    @Autowired
    private UserAction userAction;
    @Autowired
    private DriverAction driverAction;
    @Autowired
    private IDriversService iDriversService;
    @Autowired
    private IUsersService iUsersService;
    @Autowired
    private WebSocketServerDriver webSocketServerDriver;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    IUserRatingsService iUserRatingsService;

    @Autowired
    private RedisTemplate redisTemplate;
    @PostMapping("/callDriver")
    public Result<Integer> CallDriver(@RequestBody Orders orders){

        orders.setOrderDate(LocalDateTime.now());
/*        System.out.println(orders+"0000");*/
       Integer orderId= iOrdersService.addOrder(orders);
        Result<Users> usersResult = userAction.GetById(orders.getUserId());
        String phoneNumber = usersResult.getData().getPhoneNumber();
        //////////////////////////////////////////////
        Map map = new HashMap();
        map.put("type", 1);//消息类型，1表示来单提醒
        map.put("orderId", orders.getOrderId());
        map.put("departureLocation", orders.getDepartureLocation());
        map.put("destinationLocation",orders.getDestinationLocation());
        map.put("startTime",orders.getOrderDate());
        map.put("distance",orders.getDistance());
        map.put("estimatedTime",orders.getDuration());
        map.put("uuserId",orders.getUserId());
        map.put("phoneNumber",phoneNumber);
        // 通过 RabbitMQ 发布订单消息
        rabbitTemplate.convertAndSend("orderQueue", map);
        System.out.println(orders+"orders543");
        //通过WebSocket实现来单提醒，向客户端浏览器推送消息
/*        webSocketServer.sendToAllClient(JSON.toJSONString(map));*/
        webSocketServer.sendToActiveDrivers(orders.getType(), orders.getColor(),orders.getDepartureLocation(),JSON.toJSONString(map));
        ///////////////////////////////////////////////////
        clearOrderByManagerCache();
        return Result.success(orderId);
    }
/*    // 取消订单接口
    @PostMapping("/cancelOrder")
    public Result<String> CancelOrder(@RequestParam("orderId") Integer orderId){
        // 根据订单ID查询订单信息
        Orders order = iOrdersService.getById(orderId);
        if(order == null){
            return Result.error("订单不存在");
        }
        // 更新订单状态为取消
        order.setStatus("4");
        iOrdersService.updateById(order);
        return Result.success("订单取消成功");
    }
    @PutMapping("/acceptOrder")
    public Result<String> AcceptOrder(@RequestBody Orders orders){
        String key = "order_lock:" + orders.getOrderId();
        Boolean success = redisTemplate.opsForValue().setIfAbsent(key, orders.getDriverId().toString());
        if (Boolean.TRUE.equals(success)) {
        orders.setStatus("2");
        Drivers driver1=new Drivers();
        driver1.setId(orders.getDriverId());
        driver1.setStatus("2");
        Result<String> stringResult = driverAction.UpdateDriverStatus(driver1);
        System.out.println(stringResult+"980");
        boolean b = iOrdersService.updateById(orders);
        Result<Drivers> driversResult = driverAction.GetById(orders.getDriverId());
        Result<DriverVehicles> driverVehiclesResult = driverAction.GetVerById(orders.getDriverId());
        *//*        System.out.println(b+"*88888888");*//*
        //////////////////////////////////////////////
        Map map = new HashMap();
        map.put("type", 2);//消息类型，1表示来单提醒
        map.put("orderId", orders.getOrderId());
        map.put("phoneNumber",driversResult.getData().getPhoneNumber());
        map.put("licensePlate",driversResult.getData().getLicensePlate());
        map.put("vehicleType",driverVehiclesResult.getData().getVehicleType());
        map.put("color",driverVehiclesResult.getData().getColor());
        map.put("driverName",driversResult.getData().getUsername());
        //通过WebSocket实现来单提醒，向客户端浏览器推送消息
        webSocketServer.sendToUsers(JSON.toJSONString(map));
        ///////////////////////////////////////////////////
        if(b){
            return Result.success("接单成功");
        }
        return Result.error("接单失败");
    } else {
            return Result.error("订单已被其他司机抢到");
        }
    }*/
@PutMapping("/acceptOrder")
public Result<String> AcceptOrder(@RequestBody Orders orders) {
    Map<String, Object> map = new HashMap<>();
    map.put("type", 2); // 消息类型，2表示接单提醒
    map.put("orderId", orders.getOrderId());
    map.put("driverId", orders.getDriverId());

    // 通过 RabbitMQ 发布接单消息
    rabbitTemplate.convertAndSend("orderQueue", map);

    return Result.success("接单请求已发送");
}

    @PostMapping("/cancelOrder")
    public Result<String> CancelOrder(@RequestParam("orderId") Integer orderId) {
        Map<String, Object> map = new HashMap<>();
        map.put("type", 3); // 消息类型，3表示取消订单
        map.put("orderId", orderId);

        // 通过 RabbitMQ 发布取消订单消息
        rabbitTemplate.convertAndSend("orderQueue", map);

        return Result.success("取消订单请求已发送");
    }

    @GetMapping("/getOrderStatus")
    public Result<String> GetOrderStatus(@RequestParam Integer orderId){
        Orders byId1 = iOrdersService.getById(orderId);
        if(byId1.getStatus().equals("4")){
            return Result.error("该用户已取消订单......");
        }
        return Result.success();
    }
    @PostMapping("insertDT")
    public Result<String> InsertDT(@RequestBody Orders order){
        iOrdersService.updateById(order);
        return Result.success();
    }
    @GetMapping("getT")
    public Result<String>  GetT(@RequestParam Integer orderId){
        Orders byId = iOrdersService.getById(orderId);
        String durationDriver = byId.getDurationDriver();
        return Result.success(durationDriver);
    }
    @GetMapping("getT1")
    public Result<String>  GetT1(@RequestParam Integer orderId){
        Orders byId = iOrdersService.getById(orderId);
        String duration = byId.getDuration();
        return Result.success(duration);
    }
    @GetMapping("getListSE")
    public Result<?> GetListSE(@RequestParam("userId") Integer userId) {
        List<RouteFrequency> routeFrequencies = iOrdersService.getRouteFrequenciesByUserId(userId);
        if (!routeFrequencies.isEmpty()) {
            return Result.success(routeFrequencies);
        } else {
            return Result.error("历史记录加载失败......");
        }
    }
    @GetMapping("getByUserId")
    public Result<?> GetByUserId(@RequestParam Integer userId){
        List<OrderDetails> ordersAndDriverInfo = iOrdersService.getOrdersAndDriverInfo(userId);
        return Result.success(ordersAndDriverInfo);
    }
    @GetMapping("getByUserId2")
    public Result<?> GetByUserId2(@RequestParam Integer userId){
        List<Orders> orderDetailsByUserId = iOrdersService.getOrderDetailsByUserId(userId);
        return Result.success(orderDetailsByUserId);
    }
    @GetMapping("getByDriverId")
    public Result<?> GetByDriverId(@RequestParam Integer driverId){
        List<OrderDetailsDriver> ordersAndUserInfo = iOrdersService.getOrdersAndUserInfo(driverId);
        return Result.success(ordersAndUserInfo);
    }
    @GetMapping("getByDriverId2")
    public Result<?> GetByDriverId2(@RequestParam Integer driverId){
        List<Orders> orderDetailsByUserId = iOrdersService.getOrderDetailsByDriverId(driverId);
        return Result.success(orderDetailsByUserId);
    }
    @PostMapping("callPassenger")
    public Result<String> CallPassenger(@RequestParam Integer orderId){
        Map map = new HashMap();
        Orders byId = iOrdersService.getById(orderId);
        Integer driverId = byId.getDriverId();
        Drivers byId1 = iDriversService.getById(driverId);
        map.put("type", 3);
        map.put("orderId", orderId);
        map.put("driverName",byId1.getUsername());
        //通过WebSocket实现来单提醒，向客户端浏览器推送消息
        webSocketServer.sendToUsers(JSON.toJSONString(map));
        return Result.success("呼叫乘客成功");
    }
    @PostMapping("callDriver1")
    public Result<String> CallDriver1(@RequestParam Integer orderId){
        Map map = new HashMap();
        Orders byId = iOrdersService.getById(orderId);
        Integer userId = byId.getUserId();
        Users byId1 = iUsersService.getById(userId);
        map.put("type", 4);
        map.put("orderId", orderId);
        map.put("phoneNum",byId1.getPhoneNumber());
        //通过WebSocket实现来单提醒，向客户端浏览器推送消息
        webSocketServerDriver.sendToUsers(JSON.toJSONString(map));
        return Result.success("呼叫乘客成功");
    }
    @PostMapping("callPassenger1")
    public Result<String> CallPassenger1(@RequestParam Integer orderId){
        Map map = new HashMap();
        Orders byId = iOrdersService.getById(orderId);
        Integer driverId = byId.getDriverId();
        Drivers byId1 = iDriversService.getById(driverId);
        map.put("type", 5);
        map.put("orderId", orderId);
        map.put("driverName",byId1.getUsername());
        webSocketServer.sendToUsers(JSON.toJSONString(map));
        return Result.success("响应乘客成功");
    }
    @PostMapping("callPassengerArrive")
    public Result<String> CallPassengerArrive(@RequestParam Integer orderId){
        Map map = new HashMap();
        Orders byId = iOrdersService.getById(orderId);
        Integer driverId = byId.getDriverId();
        Drivers byId1 = iDriversService.getById(driverId);
        map.put("type", 6);
        map.put("orderId", orderId);
        map.put("driverName",byId1.getUsername());
        webSocketServer.sendToUsers(JSON.toJSONString(map));
        return Result.success("响应乘客成功");
    }
    @PostMapping("addAmount")
    public Result<String> AddAmount(@RequestBody Orders orders){
        boolean b = iOrdersService.updateById(orders);
        return Result.success("添加money成功");
    }
    @PutMapping("updateStatus")
    public Result<String> UpdateStatus(@RequestParam Integer orderId){
        // 根据订单ID查询订单信息
        Orders order = iOrdersService.getById(orderId);
        if(order == null){
            return Result.error("订单不存在");
        }
        order.setStatus("5");
        iOrdersService.updateById(order);
        return Result.success("订单未支付");
    }
    @PutMapping("updateStatus1")
    public Result<String> UpdateStatus1(@RequestParam Integer orderId){
        // 根据订单ID查询订单信息
        Orders order = iOrdersService.getById(orderId);
        if(order == null){
            return Result.error("订单不存在");
        }
        order.setStatus("3");
        iOrdersService.updateById(order);
        return Result.success("订单完成");
    }
    @GetMapping("getStatus5")
    public Result<String> GetStatus5(@RequestParam Integer userId){
        int count = iOrdersService.countOrdersWithStatus5(userId);
        if (count > 0) {
            return Result.error("有订单未支付");
        }
        return Result.success("可正常打车");
    }
    @GetMapping("getOrderByUserId")
    public Result<PageInfo<Orders>> GetOrderByUserId(@RequestParam Integer userId,
                                                     @RequestParam(defaultValue = "1") Integer page,
                                                     @RequestParam(defaultValue = "10") Integer size,
                                                     @RequestParam(required = false) String keyword,
                                                     @RequestParam(required = false) String keywordOrder) {
        PageHelper.startPage(page, size);
        List<Orders> ordersList = iOrdersService.getOrdersByUserId(userId, keyword,keywordOrder);
        PageInfo<Orders> pageInfo = new PageInfo<>(ordersList);
        return Result.success(pageInfo);
    }
    @GetMapping("getOrderByDriverId")
    public Result<PageInfo<Orders>> GetOrderByDriverId(@RequestParam Integer driverId,
                                                     @RequestParam(defaultValue = "1") Integer page,
                                                     @RequestParam(defaultValue = "10") Integer size,
                                                     @RequestParam(required = false) String keyword,
                                                     @RequestParam(required = false) String keywordOrder) {
        PageHelper.startPage(page, size);
        List<Orders> ordersList = iOrdersService.getOrdersByDriverId(driverId, keyword,keywordOrder);
        PageInfo<Orders> pageInfo = new PageInfo<>(ordersList);
        return Result.success(pageInfo);
    }
    @GetMapping("getOrderByManager")
    public Result<PageInfo<Orders>> GetOrderByManager( @RequestParam(defaultValue = "1") Integer page,
                                                       @RequestParam(defaultValue = "10") Integer size,
                                                       @RequestParam(required = false) String keyword,
                                                       @RequestParam(required = false) String keywordOrder) {
        // 构建Redis缓存的键
        String cacheKey = "getOrderByManager_" + page + "_" + size + "_" + keyword + "_" + keywordOrder;

        // 尝试从Redis中获取缓存数据
        PageInfo<Orders> cachedData = (PageInfo<Orders>) redisTemplate.opsForValue().get(cacheKey);
        if (cachedData != null) {
            // 如果缓存命中，则直接返回缓存数据
            return Result.success(cachedData);
        }
        PageHelper.startPage(page, size);
        List<Orders> ordersList = iOrdersService.getOrdersByManager(keyword,keywordOrder);
        PageInfo<Orders> pageInfo = new PageInfo<>(ordersList);
        redisTemplate.opsForValue().set(cacheKey, pageInfo, 5, TimeUnit.MINUTES);
        return Result.success(pageInfo);
    }
    @PostMapping("addAmount1")
    public Result<String> AddAmount1(@RequestBody Orders orders){
        iOrdersService.updateById(orders);
        return Result.success();
    }
    @GetMapping("findByDriverId")
    public Result<Drivers> FindByDriverId(@RequestParam Integer orderId){
        Orders byId = iOrdersService.getById(orderId);
        Integer driverId = byId.getDriverId();
        Drivers byId1 = iDriversService.getById(driverId);
        return Result.success(byId1);
    }
    @PostMapping("rateDriver")
    public Result<String> RateDriver(@RequestBody Orders orders){
        iOrdersService.updateById(orders);
        return Result.success();
    }
    @GetMapping("order-statistics")
    public Map<String, Object> getOrderStatistics() {
        return iOrdersService.getOrderStatistics();
    }
    @GetMapping("/rankings")
    public List<Map<String, Object>> getRankings(@RequestParam String timeRange) {
        return iOrdersService.getRanking(timeRange);
    }
    @PostMapping("addUserMsg")
    public Result<String> AddUserMsg(@RequestBody UserRatings userRatings){
        userRatings.setStatus("0");
        iUserRatingsService.save(userRatings);
        return Result.success("保存成功");
    }
    @GetMapping("/getUserRatingsByManager")
    public Result<PageInfo<UserRatings>> GetUserRatingsByManager( @RequestParam(defaultValue = "1") Integer page,
                                                     @RequestParam(defaultValue = "10") Integer size,
                                                     @RequestParam(required = false) String keyword,
                                                     @RequestParam(required = false) String keywordOrder) {

        PageHelper.startPage(page, size);
        List<UserRatings> usersList = iUserRatingsService.getUserRatingsByManager(keyword,keywordOrder);
        PageInfo<UserRatings> pageInfo = new PageInfo<>(usersList);
        return Result.success(pageInfo);
    }
    @PutMapping("/updateUserRatingsStatus")
    public Result<String> UpdateUserRatingsStatus(@RequestBody UserRatings userRatings){
        iUserRatingsService.updateById(userRatings);
        return Result.success("修改状态成功");
    }
    @PutMapping("/updateStatusSe")
    public Result<String> UpdateStatusSe(@RequestBody Orders orders){
        iOrdersService.updateById(orders);
        clearOrderByManagerCache();
        return Result.success("修改状态成功");
    }

    private void clearOrderByManagerCache() {
        // 构建清除缓存的键模式，这里假设使用模糊匹配删除相关的缓存
        String cacheKeyPattern = "getOrderByManager_*";

        // 获取所有匹配的缓存键
        Set<String> keys = redisTemplate.keys(cacheKeyPattern);

        // 删除所有匹配的缓存键
        if (keys != null && !keys.isEmpty()) {
            redisTemplate.delete(keys);
        }
    }
}
